package threadlocal;


import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ThreadLocal使用斐波那契散列法 和 拉链寻址法计算key的
 */
public class ThreadLocal_Test {

	private static ThreadLocal<SimpleDateFormat> threadLocal =
			ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * SimpleDateFormat是线程不安全的，在多线程情况下，可能会出现问题
	 */
	@Test
	public void test1() {
		for (int i = 0; i < 50; i++) {
			new Thread(() -> {
				String time1 = simpleDateFormat.format(new Date());
				try {
					Date date = simpleDateFormat.parse(time1);
					String time2 = simpleDateFormat.format(date);
					System.out.println(time1 + "---" + time2 + (time1.equals(time2)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}).start();
		}
	}

	/**
	 * 使用ThreadLocal，确保SimpleDateFormat在多线程情况下，正常使用
	 */
	@Test
	public void test2() {
		for (int i = 0; i < 50; i++) {
			new Thread(() -> {
				String time1 = threadLocal.get().format(new Date());
				try {
					Date date = threadLocal.get().parse(time1);
					String time2 = threadLocal.get().format(date);
					System.out.println(time1 + "---" + time2 + (time1.equals(time2)));
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}).start();
		}
	}

	/**
	 * 斐波那契散列法
	 * 黄金分割值 ≈ 0.618,(√5 - 1) / 2
	 */
	private static final int HASH_INCREMENT = 0x61c88647;

	@Test
	public void test3() {
		int hashCode = 0;
		for (int i = 0; i < 16; i++) {
			hashCode = i * HASH_INCREMENT + HASH_INCREMENT;
			int idx = hashCode & 15;
			System.out.println("斐波那契散列：" + idx + " 普通散列：" + (String.valueOf(i).hashCode() & 15));
		}
	}
}